﻿using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace MSUS.Kinect.SkeletonTracker.Utils
{
	public class JsonSerializer<T>
	{
		public static string ToJson(T sourceObject)
		{
			//	create a Memory stream to serialize the object into.
			using (MemoryStream ms = new MemoryStream())
			{
				//	get the JSON serializer
				DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

				//	Serialize  the object into the MemoryStream
				serializer.WriteObject(ms, sourceObject);

				//	Read the serialized string from the MemoryStream into a string and return it
				StreamReader sr = new StreamReader(ms);
				sr.BaseStream.Position = 0;
				string rawAppData = sr.ReadToEnd();
				return rawAppData;
			}
		}

		public static T FromJson(string json)
		{
			//	create a MemoryStream to hold the JSON string
			using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
			{
				//	get the JSON serializer
				DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

				//	read the JSON string and return it as the correct type.
				return (T)serializer.ReadObject(ms);
			}
		}
	}
}
